package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdLoginMapper;
import com.heima.admin.service.AdLoginService;
import com.heima.model.admin.dtos.AdminDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AdLoginServiceImpl extends ServiceImpl<AdLoginMapper, AdUser> implements AdLoginService {
    /**
     * 管理员登录
     *
     * @param dto
     */
    @Override
    public ResponseResult adminLogin(AdminDto dto) {
        //1.参数校验
        if(dto == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //2.根据用户名和密码登录
        //2.1根据用户名查询用户
        AdUser adminUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        //2.2用户为空
        if(adminUser == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //2.3手动加盐验证密码
        String passwordWithDigest = DigestUtils.md5DigestAsHex((dto.getPassword() + adminUser.getSalt()).getBytes());
        if(!passwordWithDigest.equals(adminUser.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        //3.返回token 和 用户消息
        Map<String,Object> map = new HashMap<>();
        adminUser.setPassword("");
        adminUser.setSalt("");
        map.put("user",adminUser);
        map.put("token", AppJwtUtil.getToken(Long.valueOf(adminUser.getId())));

        return ResponseResult.okResult(map);
    }
}
